package com.zhangxu.microservice.auth.biz.service.impl;

import com.zhangxu.microservice.auth.biz.dto.LoginReqDTO;
import com.zhangxu.microservice.auth.biz.dto.TokenRespDTO;
import com.zhangxu.microservice.auth.biz.service.AuthService;
import com.zhangxu.microservice.auth.biz.service.TokenService;
import com.zhangxu.microservice.auth.facade.service.EmployeeFacadeService;
import com.zhangxu.microservice.common.exception.BizException;
import com.zhangxu.microservice.employee.api.response.EmployeeAuthDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@RequiredArgsConstructor
public class AuthServiceImpl implements AuthService {

    private final EmployeeFacadeService employeeFacadeService;
    private final TokenService tokenService;
    private final PasswordEncoder passwordEncoder;

    @Override
    public TokenRespDTO login(LoginReqDTO reqDTO) {
        EmployeeAuthDTO employeeAuthDTO = employeeFacadeService.getEmployeeByAccount(reqDTO.getAccount());
        if (employeeAuthDTO == null) {
            throw new BizException("账号或密码不正确");
        }
        if (!passwordEncoder.matches(reqDTO.getPassword(), employeeAuthDTO.getPasswordCrypto())) {
            throw new RuntimeException("账号或密码不正确");
        }
        String token = tokenService.generateAndCacheToken(employeeAuthDTO.getId(), employeeAuthDTO.getName());
        return new TokenRespDTO(employeeAuthDTO.getId().toString(), employeeAuthDTO.getAccount(), employeeAuthDTO.getName(), token);
    }
}